
package net.zapasa.core.web;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.broadleafcommerce.common.locale.domain.Locale;
import org.broadleafcommerce.common.locale.service.LocaleService;
import org.broadleafcommerce.common.web.BroadleafRequestContext;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;


public class BroadleafCookieLocaleResolver extends CookieLocaleResolver {
    
	/**
     * Parameter/Attribute name for the current language
     */
    public static String LOCALE_VAR = "blLocale";
	
    @Resource(name = "blLocaleService")
    private LocaleService localeService;
    
    @Override
    protected java.util.Locale determineDefaultLocale(HttpServletRequest request) {
        java.util.Locale defaultLocale = getDefaultLocale();
       
        if (defaultLocale == null) {
        	// Busco en la request
        	defaultLocale = request.getLocale();
        	
        	// Si el idioma no es uno de los de por defecto..
        	Locale defaultBroadleafLocale = convertJavaToLocale(defaultLocale);

        	// Escribo en sesion los dos idiomas..
	        request.getSession().setAttribute(LOCALE_VAR, defaultBroadleafLocale);
	        request.getSession().setAttribute(CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME, BroadleafRequestContext.convertLocaleToJavaLocale(defaultBroadleafLocale));
        
        }
        
        return defaultLocale;
    }

	private Locale convertJavaToLocale(java.util.Locale defaultLocale) {
		Locale defaultBroadleafLocale = null;

		// Cualquier region que hable español..
		if("es".equals(defaultLocale.getLanguage())){
			 defaultBroadleafLocale = localeService.findLocaleByCode("es");
		} 
		// Cualquier requin que hable ingles..
		else if("en".equals(defaultLocale.getLanguage())){
			 defaultBroadleafLocale = localeService.findLocaleByCode("en");
		} 
		// Sino, por defecto..
		else {
			defaultBroadleafLocale =  localeService.findDefaultLocale();
		}

		return defaultBroadleafLocale;
	}

    
}
